package com.hrabun.goodmorningalarm;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Map;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.ToggleButton;

public class AddNewAlarm extends Activity implements OnClickListener, OnCheckedChangeListener {

	private final int HANDLER_PING_RADIO = 1;
	
	Button btnOK;
	Button btnCancel;
	TimePicker timePicker;
	ToggleButton btnMonday;
	ToggleButton btnTuesday;
	ToggleButton btnWednesday;
	ToggleButton btnThursday;
	ToggleButton btnFriday;
	ToggleButton btnSaturday;
	ToggleButton btnSunday;
	TextView txtRadiolabel;
	Spinner spinRadios;
	ToggleButton btnRadioPreview;
	// ArrayList<RadioStation> radioStations;
	ArrayList<Map<String, String>> radioStations;
	Activity context;
	ArrayList<RadioStation> radios;
	RadioStation radio;
	Handler hand;

	int mode;
	String itemId = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		this.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        this.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
		setContentView(R.layout.add_new_alarm);
		this.context = this;

		registerControls();
		setFont();
		registerListeners();

		Intent intent = getIntent();
		mode = intent.getExtras().getInt("mode");

		switch (mode) {
		case Global.DIALOG_TIME_ADD: {
			configureAsAddAlarm();

		}
			break;
		case Global.DIALOG_TIME_CHANGE: {
			itemId = (String) intent.getExtras().get("id");
			configureAsChangeAlarm(itemId);
			this.setTitle("Change existing alarm");
		}
			break;

		default:
			break;
		}

		
	}

	private void registerControls() {
		btnOK = (Button) findViewById(R.id.btnAddAlarmOK);
		btnCancel = (Button) findViewById(R.id.btnAddAlarmCancel);
		timePicker = (TimePicker) findViewById(R.id.addAlarmTimePicker);
		timePicker.setIs24HourView(Global.pref_is24Mode());
		hand = new Handler(callback);
		

		/* Days Buttons */
		btnMonday = (ToggleButton) findViewById(R.id.btnMonday);
		btnTuesday = (ToggleButton) findViewById(R.id.btnTuesday);
		btnWednesday = (ToggleButton) findViewById(R.id.btnWednesday);
		btnThursday = (ToggleButton) findViewById(R.id.btnThursday);
		btnFriday = (ToggleButton) findViewById(R.id.btnFriday);
		btnSaturday = (ToggleButton) findViewById(R.id.btnSaturday);
		btnSunday = (ToggleButton) findViewById(R.id.btnSunday);
		spinRadios = (Spinner) findViewById(R.id.spinRadios);
		txtRadiolabel = (TextView) findViewById(R.id.txtRadioLabel);
		btnRadioPreview = (ToggleButton) findViewById(R.id.btnAddAlarmPreviewRadio);
		
		if (!Global.pref_isSundayStarting()) {
			LinearLayout lin = (LinearLayout) findViewById(R.id.layout_AddAlarmDays);
			lin.removeView(btnSunday);
			lin.addView(btnSunday);
		}
	}

	private void setFont() {
		btnOK.setTypeface(Global.setFontRibeye());
		btnCancel.setTypeface(Global.setFontRibeye());
		btnSunday.setTypeface(Global.setFontRibeye());
		btnMonday.setTypeface(Global.setFontRibeye());
		btnTuesday.setTypeface(Global.setFontRibeye());
		btnWednesday.setTypeface(Global.setFontRibeye());
		btnThursday.setTypeface(Global.setFontRibeye());
		btnFriday.setTypeface(Global.setFontRibeye());
		btnSaturday.setTypeface(Global.setFontRibeye());
		txtRadiolabel.setTypeface(Global.setFontRibeye());
		
	}
	
	private void configureAsAddAlarm() {
		Calendar cal = Calendar.getInstance();
		timePicker.setCurrentHour(cal.get(Calendar.HOUR_OF_DAY));
		timePicker.setCurrentMinute(cal.get(Calendar.MINUTE));
		fillRadioList();
		this.setTitle("Add new alarm");
	}

	private void configureAsChangeAlarm(String id) {
		AlarmItem item = new AlarmItem();
		item = item.getAlarmItemById(id);
		fillRadioList();
		Calendar cal = Calendar.getInstance();
		cal.setTime(item.alarmTime);
		timePicker.setCurrentHour(cal.get(Calendar.HOUR_OF_DAY));
		timePicker.setCurrentMinute(cal.get(Calendar.MINUTE));
		btnMonday.setChecked(item.monday);
		btnTuesday.setChecked(item.tuesday);
		btnWednesday.setChecked(item.wednesday);
		btnThursday.setChecked(item.thursday);
		btnFriday.setChecked(item.friday);
		btnSaturday.setChecked(item.saturday);
		btnSunday.setChecked(item.sunday);

		if (! item.getRadioAssignedID().equalsIgnoreCase("")) {
			spinRadios.setSelection(Integer.valueOf(item.getRadioAssignedID())-1);
		}
		this.setTitle("Change existing alarm");
	}

	private void registerListeners() {
		btnOK.setOnClickListener(this);
		btnCancel.setOnClickListener(this);
		btnRadioPreview.setOnCheckedChangeListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnAddAlarmOK: {
			Intent intent = new Intent();
			intent.putExtra("mode", mode);
			if (itemId != null) {
				intent.putExtra("id", itemId);
			}

			intent.putExtra("hours", timePicker.getCurrentHour());
			intent.putExtra("mins", timePicker.getCurrentMinute());
			intent.putExtra("mon", btnMonday.isChecked());
			intent.putExtra("tue", btnTuesday.isChecked());
			intent.putExtra("wed", btnWednesday.isChecked());
			intent.putExtra("th", btnThursday.isChecked());
			intent.putExtra("fri", btnFriday.isChecked());
			intent.putExtra("sat", btnSaturday.isChecked());
			intent.putExtra("sun", btnSunday.isChecked());
			intent.putExtra("radio", spinRadios.getSelectedItemId()+1);

			setResult(RESULT_OK, intent);
			btnRadioPreview.setChecked(false);
			finish();
		}
			break;
		case R.id.btnAddAlarmCancel: {
			setResult(RESULT_CANCELED);
			btnRadioPreview.setChecked(false);
			finish();
		}
			break;
		default:
			break;
		}

	}

	/**
	 * Filling Radio Stations spinner 
	 */
	private void fillRadioList() {
		RadioStationDAO radioDAO = new RadioStationDAO(this);
		radios = radioDAO.getAllRadioStations();
		ArrayList<String> radioNames = new ArrayList<String>();
		for (RadioStation radioStation : radios) {
			radioNames.add(radioStation.getStationName());
		}
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, radioNames);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		spinRadios.setAdapter(adapter);
		spinRadios.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				Toast.makeText(
						context,
						"Selection id = "
								+ spinRadios.getSelectedItemPosition(),
						Toast.LENGTH_LONG).show();
				btnRadioPreview.setChecked(false);

			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}
		});

	}
	
	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		switch (buttonView.getId()) {
		case R.id.btnAddAlarmPreviewRadio:
		{
			if (isChecked) {
				if (radio != null) {
					radio.stopRadio();
				}
				radio = new RadioStation();
				radio = radio.getStationById(String.valueOf(spinRadios.getSelectedItemId()+1));
				startPingingRadioStation();
				radio.playRadio();
			} else {
				if (radio != null) {
					radio.stopRadio();
					stopPingingRadioStation();
				}
			}
		}	break;

		default:
			break;
		}
	}
	
	private void startPingingRadioStation() {
		hand.sendEmptyMessageDelayed(HANDLER_PING_RADIO, 0);
	}
	
	private void stopPingingRadioStation() {
		hand.removeMessages(HANDLER_PING_RADIO);
	}
	
	Handler.Callback callback = new Callback() {
		
		@Override
		public boolean handleMessage(Message msg) {
			switch (msg.what) {
			case HANDLER_PING_RADIO:
			{
				if (radio != null) {
					boolean res = radio.isRadioPlaying();
					if (res) {
						btnRadioPreview.setEnabled(true);
					} else {
						btnRadioPreview.setEnabled(false);
						hand.sendEmptyMessageDelayed(HANDLER_PING_RADIO, 1 * 1000);
					}
				}				
			}
				break;

			default:
				break;
			}
			return false;
		}
	};
}
